<?php
/**
 * Helper which is responsible for sending emails.
 *
 * @author  Marcin Klawitter <marcin.klawitter@gmail.com>
 */
class Kohana_Mailer
{
	private $_config;
	public function __construct($group = 'default')
	{
		require_once Kohana::find_file('vendor/phpmailer', 'class.phpmailer');
		$this->_config = Kohana::$config->load('mailer.'.$group);
	
	}

	/**
	 * Send message.
	 * @example send(array('a@a.com' => 'a mame'), 'subject', 'content', array('/path/to/file1','/path/to/file2'));
	 *
	 * @param       array  $to  which message is being send to
	 * @param       string      Email subject
	 * @param       string      Email body
	 * @param       array  $cc  which message is being cc to
	 * @return      boolean
	 */
	public function send($to, $subject, $body, $attechment = array(), $cc = array(), $bcc = array(), $reply_to = array())
	{

		$mail = new PHPMailer();
		$mail->IsMail();

		if($this->_config['mode'] == 'smtp')
		{
			require_once Kohana::find_file('vendor/phpmailer', 'class.smtp');
			$smtp = $this->_config['smtp'];
			$mail->IsSMTP();
			$mail->SMTPAuth = true;
			$mail->SMTPSecure = $smtp['secure'];
			$mail->Host = $smtp['host'];
			$mail->Port = $smtp['port'];
			$mail->Username = $smtp['username'];
			$mail->Password = $smtp['password'];
		}
		
		$mail->CharSet = "UTF-8";
		$from = $this->_config['from'];
		$mail->From = $from['mail'];
		$mail->FromName = $from['name'];

		$mail->Subject = $subject;
		$mail->Body = $body;
		//$mail->AltBody      = nohtml($body);

		$mail->isHTML(true);
		$mail->WordWrap = 50;

		$to = to_array($to);
		foreach ($to as $e => $name)
		{
			if (strpos($e, '@') === FALSE)
				$mail->AddAddress($name);
			else
				$mail->AddAddress($e, $name);
		}

		if (!empty($cc))
		{
			$cc = to_array($cc);
			foreach ($cc as $e => $name)
			{
				if (strpos($e, '@') === FALSE)
					$mail->AddCC($name);
				else
					$mail->AddCC($e, $name);
			}
		}

		if (!empty($bcc))
		{
			$bcc = to_array($bcc);
			foreach ($bcc as $e => $name)
			{
				if (strpos($e, '@') === FALSE)
					$mail->AddBCC($name);
				else
					$mail->AddBCC($e, $name);
			}
		}

		if (!empty($reply_to))
		{
			$reply_to = to_array($reply_to);
			foreach ($reply_to as $e => $name)
			{
				if (strpos($e, '@') === FALSE)
					$mail->addReplyTo($name);
				else
					$mail->addReplyTo($e, $name);
			}
		}

		if (!empty($attechment))
		{
			$attechment = to_array($attechment);
			foreach ($attechment as $filename)
				$mail->addAttachment($filename);
		}
		return $mail->Send();
	}
}
